package com.openunion.cordova.plugins.unionpay;

import android.util.Log;
import android.content.Intent;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaWebView;
import com.unionpay.UPPayAssistEx;
import com.unionpay.uppay.PayActivity;
import com.unionpay.UPQuerySEPayInfoCallback;
import android.os.Bundle;

/**
 * This class echoes a string called from JavaScript.
 */
public class UnionPay extends CordovaPlugin {
    private final static String LOG_TAG = "com.openunion.cordova.plugins.unionpay";

    /**
     * Payment mode, defaults to "00"
     *   * "00" => Official
     *   * "01" => Test
     */
    public CallbackContext g_unionpayCallbackContext;
    public String g_tn;
    public String g_test_mode;
	public String g_seType;
    
    @Override
    public void pluginInitialize() {
        super.pluginInitialize();
    }

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        Log.d(LOG_TAG, String.format("Invoking action \"%s\".", action));

        g_unionpayCallbackContext = callbackContext;
        cordova.setActivityResultCallback(this);

        if (action.equals("starPay")) {
            try{
                String tn = args.getString(0);
                String test_mode = args.getString(1);
                if(test_mode == null || test_mode.isEmpty()) test_mode = "00";
                if(tn == null || tn.isEmpty()){
                  callbackContext.error("parameter tn is null error");
                }else{
                  Log.d(LOG_TAG, String.format("Start payment with transaction number \"%s\" and mode \"%s\".", tn, test_mode));
                  UPPayAssistEx.startPay(cordova.getActivity(), null, null, tn, test_mode);
                }
            } catch (Exception e) {
                callbackContext.error(e.getMessage());
            }

            return true;
        }
        else
        if (action.equals("starSEPay")) {
            try{
                String tn = args.getString(0);
                String test_mode = args.getString(1);
                if(test_mode == null || test_mode.isEmpty()) test_mode = "00";
                if(tn == null || tn.isEmpty()){
                  callbackContext.error("parameter tn is null error");
                } else {
                  Log.d(LOG_TAG, String.format("Start payment with transaction number \"%s\" and mode \"%s\".", tn, test_mode));
				  g_tn = tn;
				  g_test_mode = test_mode;
                  UPQuerySEPayInfoCallback callback = new UPQuerySEPayInfoCallback() {
                    @Override
                    public void onResult(String SEName, String seType, int cardNumbers, Bundle reserved) {
                        // 该方法在手机Pay正常情况下回调
						g_seType = seType;
                        UPPayAssistEx.startSEPay(cordova.getActivity(), null, null, g_tn, g_test_mode, seType);                       
                    }
                    @Override
                    public void onError(String SEName, String seType, String errorCode,String errorDesc) {
                        // 该方法在手机Pay异常情况下回调
						if ("02".equals(errorCode)) g_unionpayCallbackContext.error("请先在手机的钱包APP中绑卡！");
                        else g_unionpayCallbackContext.error("暂不支持该手机钱包: " + errorDesc);
                    }
                  };
                  int ret = UPPayAssistEx.getSEPayInfo(cordova.getActivity(), callback);
                }
            } catch (Exception e) {
                //callbackContext.error("Exception: " + e.getMessage());
                callbackContext.error("暂不支持该手机钱包: [Exception] " + e.getMessage());
            }

            return true;
        }        
        return false;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (null == intent) {
			if(g_seType != null && !g_seType.isEmpty()) g_unionpayCallbackContext.error("Fail to get result with intent");
            return;
        }
        /*
         * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
         */
        try {
            JSONObject resultJson = new JSONObject();
            String payResult = intent.getExtras().getString("pay_result");
            resultJson.put("pay_result", payResult);
            if (payResult.equalsIgnoreCase("success")) {
              if (intent.hasExtra("result_data")) {
                  String resultData = intent.getExtras().getString("result_data");
                  JSONObject dataJson = new JSONObject(resultData);
                  resultJson.put("data",dataJson.getString("data"));
                  resultJson.put("sign",dataJson.getString("sign"));
              }
            }
            g_unionpayCallbackContext.success(resultJson.toString());
        } catch (JSONException e) {
            g_unionpayCallbackContext.error(e.getMessage());
        }
    }
}
